package cn.edu.nuc.chat.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.UUID;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTextArea;

import cn.edu.nuc.chat.model.InitInfo;
import cn.edu.nuc.chat.model.User;
import cn.edu.nuc.chat.util.Token;

public class TCPClient implements Runnable {
	//自己唯一UUID
	public final static String MY_UUID = UUID.randomUUID().toString();
	//当前聊天对象UUID
	public static String TO_UUID = "";
	
	private static Socket client = null;
	private BufferedReader reader = null;
	private JTextArea textMessage = null;
	private static JList<User> users = null;
	private static String nickName = null;
	public TCPClient(JTextArea textMessage, JList<User> users ){
		this.textMessage = textMessage;
		TCPClient.users = users;
	}
	
	/**
	 * 不间断收听服务端消息
	 */
	@Override
	public void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
			//login:sdf879sdfs-sdfs8s-sdfs7k-skysdf:张三
			send("login" + Token.DELIM + MY_UUID + Token.DELIM + nickName );
			
			DefaultListModel<User> model = (DefaultListModel<User>)users.getModel();
			while( true ){
				
				String msg = reader.readLine();
				if( msg == null || "bye".equalsIgnoreCase(msg)){
					break;
				} else if( msg != null && ! "".equals(msg)){
					StringTokenizer st = new StringTokenizer(msg, Token.DELIM);
					String command = st.nextToken();
					String uuid = st.nextToken().trim();
					User u = new User(uuid);
					switch( command ){
						case "login":
							//昵称
							u.setNickName(st.nextToken());
							add(u, model);
							break;
						case "msg":
							//如果为消息, 该uuid则为发送方uuid
							//昵称	
							String nickName = st.nextToken();
							StringBuilder sb = new StringBuilder();
							sb.append( nickName ); 	
							sb.append("说:\n");
							sb.append(st.nextToken());	//消息内容
							
							u.setNickName(nickName);
							add(u, model);
							textMessage.setText( textMessage.getText() + "\n" + sb.toString() );
							break;
						case "logout":
							//移除
							model.removeElement( u );
							break;
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch ( Exception e){
			System.out.println("链接被中断" + e.getMessage());
		} finally {
			try {
				if( client != null && ! client.isClosed() )
					client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	
	private static void add(User u, DefaultListModel<User> model){
		
		if( model.contains( u ) ){
			//如果该用户已存在,修改其昵称
			Enumeration<User> users = model.elements();
			while( users.hasMoreElements() ){
				User user = users.nextElement();
				if( user.equals( u ) ){
					user.setNickName( u.getNickName() );
					break;
				}
			}
		} else {
			//如果该用户不在列表,则将其加入列表
			model.addElement( u );
		}
	}
	
	//发送消息
	public synchronized static boolean send( String msg){
		try {
			new PrintWriter(client.getOutputStream(), true).println(msg);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean start(InitInfo info, JTextArea textMessage, JList<User> users){
		try {
			client = new Socket(info.getHost(), info.getPort());
			
			nickName = info.getUser().getNickName();
			//启动收消息线程
			new Thread( new TCPClient(textMessage, users) ).start();
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	public static boolean stop(){
		if( client != null && ! client.isClosed()){
			try {
				send( "logout" + Token.DELIM + MY_UUID );
				
				//移除所有在线用户
				users.removeAll();
				return true;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}

}
